<template>
  <view class="group-home">
    <view class="top">
      <span class="back" @click='back'>
        <image src="../../static/images/common/back1.png" mode=""></image>
      </span>
      <view class="right">
        <image src="../../static/images/group/more1.png" mode=""></image>
      </view>
    </view>

    <view class="top bgbar" :animation="info.animation">
      <span class="back" @click='back'>
        <image src="../../static/images/common/back.png" mode=""></image>
      </span>
      <view class="right">
        <image src="../../static/images/group/more.png" mode=""></image>
      </view>
    </view>

    <view class="bg">
      <image :src="info.groupimg" mode="aspectFill"></image>
    </view>

    <view class="main">
      <view class="main-inner">
        <view class="info">
          <view class="ginfo">
            <view class="name">{{info.groupdetail.groupname}}</view>
            <view class="time">{{formatBirth(info.groupdetail.time)}}</view>
          </view>
          <view class="notice">{{info.groupdetail.notice}}</view>
        </view>
        <view class="member clearfix">
          <view class="up">
            <view class="title">群成员</view>
            <view class="right">
              <view class="more" @click="changeClose">管理群成员</view>
              <image src="../../static/images/common/more.png" mode=""></image>
            </view>
          </view>
          <view class="member-ls clearfix">
            <view class="member-li" v-for="(item,index) in info.groupMember" :key="index">
              <view class="img">
                <image v-show="info.isShowClose && item.userid != info.groupcreatedid" class="del"
                  @click="deleteUser(item)" src="../../static/images/group/delete.png" mode=""></image>
                <image :src="item.imgurl" class="user-img" mode="aspectFit"></image>
              </view>
              <view class="name" v-if="item.usernameInGroup">{{item.usernameInGroup}}</view>
              <view class="name" v-else>{{item.username}}</view>
            </view>
            <view class="member-li" @click="gotoyaoqing">
              <view class="img">
                <image src="../../static/images/group/add.png" class="user-add" mode="aspectFit"></image>
              </view>
              <view class="names">邀请</view>
            </view>
          </view>
        </view>

        <view class="mitem">
          <view class="group" @click="changeShow('群名称', info.groupdetail.groupname)">
            <view class="left">
              <span class='sin'>群名称：</span>
              <span class="name">{{info.groupdetail.groupname}}</span>
            </view>
            <view class="right">
              <image src="@/static/images/common/more.png" mode=""></image>
            </view>
          </view>
          <view class="group-img">
            <view class="left" @click="updatedPic">
              <span class='avater'>群头像</span>
              <image :src="info.groupimg" mode=""></image>
              <div v-if="info.isShowPic">
                <qf-image-cropper :width="500" :height="500" :radius="30" @crop="handleCrop"></qf-image-cropper>
              </div>
            </view>
            <view class="right" @click="seePic">
              <image src="@/static/images/common/more.png" mode=""></image>
            </view>
          </view>
          <view class="group" @click="changeShow('群公告', info.groupdetail.notice)">
            <view class="left">
              <span class='sin'>群公告：</span>
              <span class="name">{{info.groupdetail.notice}}</span>
            </view>
            <view class="right">
              <image src="@/static/images/common/more.png" mode=""></image>
            </view>
          </view>
          <view class="group" @click="changeShow('群内名', info.groupdetail.usernameInGroup)">
            <view class="left">
              <span class='sin'>群内名：</span>
              <span class="name">{{info.groupdetail.usernameInGroup}}</span>
            </view>
            <view class="right">
              <image src="@/static/images/common/more.png" mode=""></image>
            </view>
          </view>
          <view class="group">
            <view class="left">
              <span class='sin'>消息免打扰</span>
            </view>
            <view class="right">
              <switch @change="switchChange" color="#FFCC33" style="transform:scale(0.7)" />
            </view>
          </view>
        </view>


        <view class="btn">
          <button type="warn" v-if="info.userid == info.groupcreatedid" @click="outGroup">解散群</button>
          <button type="warn" v-if="info.userid != info.groupcreatedid" @click="getout">退出群聊</button>
        </view>
      </view>
    </view>
  </view>

  <popupVue @getNewData='getNewData' :tempUserInfo='tempUserInfo' :isShowPopup='info.isShowPopup'></popupVue>
</template>

<script setup>
  import popupVue from '@/components/popup/popup.vue'
  import {
    onLoad,
    onReady,
    onShow,
    onPageScroll
  } from '@dcloudio/uni-app'
  import {
    reactive,
    getCurrentInstance
  } from 'vue'
  import {
    useUserStore
  } from '@/store/user.js'
  import {
    requestNet
  } from '@/api/base.js'
  import {
    formatBirth
  } from '@/utils/formatDate.js'

  const instance = getCurrentInstance()
  const user = useUserStore() //创建仓库
  const info = reactive({
    groupid: null, //群id
    groupcreatedid: null, //群创建者id
    groupimg: '', //群头像
    userid: null, //当前登录用户id
    groupMember: [], //群成员数组
    groupdetail: {}, //群详情对象
    top: 0,
    animation: {},
    isShowPic: false, //控制是否裁剪
    token: '',
    isShowPopup: false, //是否显示弹出层
    isShowClose: false //是否显示删除用户
  })
  let tempUserInfo = reactive({
    propsName: '',
    attr: '',
    gid: null
  })

  function gotoyaoqing() {
    uni.navigateTo({
      url: `/pages/addFiendInGroup/addFiendInGroup?gid=${info.groupid}`
    })
  }

  //退出群聊
  function getout() {
    uni.showModal({
      title: '提示',
      content: '是否要退出群聊',
      success: function(res) {
        if (res.confirm) {
          requestNet({
            url: '/group/deletegroupmember',
            data: {
              uid: info.userid
            },
            method: 'POST',
            header: {
              token: info.token
            }
          }).then(res => {
            let code = res.data.code
            if (code == 200) {
              uni.showToast({
                title: '退出成功',
                icon: 'success'
              })
              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/home/home'
                })
              }, 1000)
            }
          }).catch(err => {
            uni.showToast({
              title: err,
              icon: 'error'
            })
          })
        } else if (res.cancel) {}
      }
    });
  }

  //删除某一个群成员
  function deleteUser(item) {
    uni.showModal({
      title: '提示',
      content: '是否要踢出该用户',
      success: function(res) {
        if (res.confirm) {
          requestNet({
            url: '/group/deletegroupmember',
            data: {
              uid: item.userid
            },
            method: 'POST',
            header: {
              token: info.token
            }
          }).then(res => {
            let code = res.data.code
            if (code == 200) {
              uni.showToast({
                title: '踢出成功',
                icon: 'success'
              })
              getGroupMember()
            }
          }).catch(err => {
            uni.showToast({
              title: err,
              icon: 'error'
            })
          })
        } else if (res.cancel) {}
      }
    });
  }

  //解散群
  function outGroup() {
    uni.showModal({
      title: '提示',
      content: '是否要解散该群',
      success: function(res) {
        if (res.confirm) {
          requestNet({
            url: '/group/outGroup',
            data: {
              gid: info.groupid
            },
            method: 'POST',
            header: {
              token: info.token
            }
          }).then(res => {
            let code = res.data.code
            if (code == 200) {
              uni.showToast({
                title: '解散成功',
                icon: 'success'
              })
              setTimeout(() => {
                uni.navigateTo({
                  url: '/pages/home/home'
                })
              }, 1000)
            }
          }).catch(err => {
            uni.showToast({
              title: err,
              icon: 'error'
            })
          })
        } else if (res.cancel) {}
      }
    });
  }

  function changeClose() {
    info.isShowClose = !info.isShowClose
  }

  function updatedPic() {
    info.isShowPic = true
  }
  //获取群详细数据
  function getGroupDetail() {
    requestNet({
      url: '/group/getgroupdetail',
      data: {
        gid: info.groupid,
        uid: info.userid
      },
      method: 'GET',
      header: {
        token: info.token
      }
    }).then(res => {
      let code = res.data.code
      let result = res.data.data
      if (code == 200) {
        info.groupdetail = result[0]
        info.groupdetail.imgurl = instance.proxy.serverUrl + info.groupdetail.imgurl
        info.groupcreatedid = info.groupdetail.createid
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //获取群成员数据
  function getGroupMember() {
    requestNet({
      url: '/group/getgroupmember',
      data: {
        gid: info.groupid
      },
      method: 'GET',
      header: {
        token: info.token
      }
    }).then(res => {
      let code = res.data.code
      let result = res.data.data
      if (code == 200) {
        info.groupMember = result
        for (let i = 0; i < result.length; i++) {
          info.groupMember[i].imgurl = instance.proxy.serverUrl + info.groupMember[i].imgurl
        }
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //裁剪图片  点击确认之后
  function handleCrop(e) {
    info.groupimg = e.tempFilePath
    //上传图片
    uni.uploadFile({
      url: `${instance.proxy.serverUrl}/files/upload`, //仅为示例，非真实的接口地址[后端接口地址]
      filePath: e.tempFilePath,
      name: 'file',
      formData: {
        url: 'group',
        name: new Date().getTime().toString()
      },
      header: {
        token: info.token
      },
      success: (uploadFileRes) => {
        console.log(uploadFileRes)
        let picpath = uploadFileRes.data
        updateUser(picpath, 'imgurl')
      }
    });
    uni.previewImage({
      urls: [e.tempFilePath],
      current: 0
    });
    info.isShowPic = false
  }
  //显示弹出层
  function changeShow(propsName, data) {
    tempUserInfo.propsName = propsName
    tempUserInfo.attr = data
    tempUserInfo.gid = info.groupid
    info.isShowPopup = !info.isShowPopup
  }

  //处理子组件返回的数据
  function getNewData(data) {
    console.log(data)
    let {
      propsName,
      value
    } = data
    if (propsName == '群名称') {
      info.groupname = value
      updateUser(value, 'groupname')
    } else if (propsName == '群内名') {
      info.gourpmarkname = value
      requestNet({
        url: '/group/updateUserMarkNameInGroup',
        data: {
          uid: info.userid,
          gid: info.groupid,
          name: value,
        },
        method: 'POST',
        header: {
          token: info.token
        }
      }).then(res => {
        let code = res.data.code
        if (code == 200) {
          uni.showToast({
            title: '修改成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: res.data.message,
            icon: 'error'
          })
          return;
        }
      }).catch(err => {
        uni.showToast({
          title: err,
          icon: 'error'
        })
      })
    } else if (propsName == '群公告') {
      info.natice = value
      updateUser(value, 'notice')
    }
  }

  //修改数据
  function updateUser(e, t) {
    requestNet({
      url: '/group/updategroup',
      data: {
        groupid: info.groupid,
        data: e,
        type: t
      },
      method: 'POST',
      header: {
        token: info.token
      }
    }).then(res => {
      let code = res.data.code
      if (code == 200) {
        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: res.data.message,
          icon: 'error'
        })
        return;
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //查看群头像大图
  function seePic() {
    console.log(13)
    uni.previewImage({
      urls: [info.groupimg],
      longPressActions: {
        itemList: ['发送给朋友', '保存图片', '收藏'],
        success: function(data) {
          console.log(data)
        },
        fail: function(err) {
          console.log(err.errMsg);
        }
      }
    });
  }

  //获取缓存数据
  function getStorage() {
    if (Object.keys(user.userinfo).length != 0) { //如果有数据，登录过了
      info.token = user.token
    } else { //否则跳转到登录页面
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
  }

  //获取距离顶部高度
  function getTop() {
    const query = uni.createSelectorQuery().in(this);
    query.select('.main-inner').boundingClientRect(data => {
      info.top = parseInt(data.top)
    }).exec();
  }
  //顶部切换动画
  function addAnimate() {
    let animation = uni.createAnimation({
      duration: 300,
      timingFunction: 'linear',
    })
    if (info.top < 50) {
      animation.opacity(1).step()
    } else animation.opacity(0).step()
    info.animation = animation.export()
  }

  function back() {
    uni.navigateBack({
      delta: 1
    })
  }
  onShow(() => {
    getGroupMember()
  })
  onLoad((e) => {
    if (e != null) {
      info.groupid = parseInt(e.gid)
      info.groupimg = e.img
      info.userid = parseInt(e.uid)
    }
    getStorage()
    getGroupDetail()
    // getGroupMember()
  })

  //监听页面滚动
  onPageScroll(() => {
    getTop()
    addAnimate()
  })

  onReady(() => {
    getTop()
  })
</script>

<style lang="scss" scoped>
  @import '../../assets/css/top.scss';

  .bgbar {
    opacity: 0;
    background-color: white;
  }

  .group-home {
    .top {
      padding: 0 20rpx;
      display: flex;
      // position: relative;
      position: fixed;
      align-items: center;
      height: 88rpx;

      .back {
        display: inline-block;
        height: 48rpx;
        width: 48rpx;

        image {
          height: 100%;
          width: 100%;
        }
      }

      .title {
        position: absolute;
        //居中显示
        transform: translateX(-50%);
        left: 50%;

        font-size: 36rpx;
        font-weight: 700;
      }

      .right {
        width: 60rpx;
        height: 20rpx;
        line-height: 20rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .bg {
      width: 100%;
      height: 100%;
      position: fixed;
      background: #fff;
      // top: 88rpx;
      top: 0;
      left: 0;
      z-index: 0;

      image {
        width: 100vw;
        height: 40vh;
        border-radius: 0;
      }
    }

    .main {
      position: relative;
      padding-top: 350rpx;
      z-index: 1;

      &-inner {
        width: 100%;
        min-height: 720rpx;
        background-color: #fff;
        border-radius: 40rpx 40rpx 0 0;
        padding-bottom: 20rpx;

        .info {
          padding: 20rpx 30rpx;
          border-bottom: 1px solid #eee;

          .ginfo {
            display: flex;
            justify-content: space-between;

            .name {
              font-size: 48rpx;
              font-weight: 600;
              color: #272832;
              line-height: 66rpx;
            }

            .time {
              font-size: 28rpx;
              line-height: 66rpx;
              color: rgba(39, 40, 50, .3);
            }
          }

          .notice {
            padding-top: 20rpx;
            color: #272832;
            line-height: 40rpx;
            display: -webkit-box;
            clear: both;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
        }

        .member {
          clear: both;
          padding: 0 20rpx;

          .up {
            margin-top: 20rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 20rpx;
            border-bottom: 1px solid #eee;

            .title {
              font-size: 36rpx;
              font-weight: 600;
            }

            .right {
              display: flex;
              align-items: center;

              .more {
                margin-right: 15rpx;
                font-weight: 400;
                color: rgba(39, 40, 50, .6);
              }

              image {
                width: 16rpx;
                height: 28rpx;
              }
            }
          }

          .member-ls {
            width: 100%;
            padding: 20rpx 16rpx;
          }

        }
      }


      .mitem {
        padding: 0 20rpx;

        .group {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 32rpx;

          .left {
            .sin {
              font-weight: 600;
            }

            .name {
              font-family: PingFangSC-Regular;
              font-size: 16px;
              color: rgba(39, 40, 50, 0.60);
              letter-spacing: -0.55px;
              font-weight: 400;
            }
          }
        }
      }

      .btn {
        margin: 20rpx 20rpx;
      }
    }
  }

  .group-img {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 32rpx;
    border-bottom: 2rpx solid var(--border-color);
    height: 130rpx;

    .left {
      font-weight: 600;

      .avater {
        margin-right: 20rpx;
      }

      image {
        width: 100rpx;
        height: 100rpx;
      }
    }
  }

  .group {
    height: 110rpx;
    border-bottom: 2rpx solid var(--border-color);

    .left {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .right {
    image {
      width: 28rpx;
      height: 28rpx;
    }
  }

  .member-li {
    margin-bottom: 28rpx;
    text-align: center;
    width: 20%;
    border-radius: 10px;
    float: left;

    .img {
      position: relative;
      display: inline-block;
      width: 104rpx;
      height: 104rpx;
      background: #f8da2f;
      border-radius: 10px;

      .user-img {
        width: 104rpx;
        height: 104rpx;
      }

      .del {
        position: absolute;
        width: 40rpx;
        height: 40rpx;
        right: -10rpx;
        top: -10rpx;
        z-index: 2;
      }
    }

    .name {
      padding: 5rpx 8rpx;
      color: #272832;
      font-size: 28rpx;
      line-height: 35rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;
    }

    .user-add {
      position: absolute;
      width: 50rpx;
      height: 50rpx;
      top: 25%;
      left: 50%;
      transform: translateX(-50%);
      box-sizing: border-box;
    }
  }

  .image-cropper[data-v-6592bb66] {
    z-index: 30;
  }
</style>
